﻿using dz.u9.jky.schema.Common;
using System.Collections.Generic;
using System.Data;
using UFIDA.U9.Base.Organization;
using UFIDA.U9.CBO.Pub.Controller;
using UFSoft.UBF.Util.DataAccess;

namespace dz.inner.jky.api.service
{
    internal class DocIssueService : BaseService
    {
        public U9CResult Issued(DocIssue dto)
        {
            return util.U9Invoke(__Issued, dto);
        }

        private U9CResult __Issued(DocIssue dto)
        {
            U9CResult result = new U9CResult();

            OnlineSendObjs bp = new OnlineSendObjs();

            bp.IDs = dto.Ids;
            bp.FullName = dto.EntityName;
            bp.FromOrg = new Organization.EntityKey(Organization.FindByCode(dto.FromOrg).ID);
            bp.ToOrgList = GetToOrgs(GetOrgs(dto));

            bp.Do();

            result.IsSuccess = true;

            return result;
        }

        

        private List<long> GetOrgs(DocIssue dto)
        {
            List<long> ids = new List<long>();
            IDataReader dataReader;

            string sql = $@"select id,code from Base_Organization where CreatedBy <>'EA' and code <> '{dto.FromOrg}'";

            if(dto.ToOrgs == null) dto.ToOrgs = new List<string>();

            DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null, out dataReader);

            while (dataReader.Read())
            {
                string code = dataReader.GetString(1);

                if (!dto.ToOrgs.Contains(code))
                {
                    long id = dataReader.GetInt64(0);
                    ids.Add(id);
                }
            }

            dataReader.Close();

            return ids;
        }

        private List<Organization.EntityKey> GetToOrgs(List<long> ids)
        {
            List<Organization.EntityKey> rtn = new List<Organization.EntityKey>();

            foreach (long id in ids) 
            {
                rtn.Add( new Organization.EntityKey(id));
            }

            return rtn;
        }
    }
}
